(function(){
	/**
	 * 重写jquery的ajax请求，逻辑：先将原ajax请求赋值另外的函数，在重写新ajax方法
	 */
	$.oldAjax=$.ajax;
	$.ajax=function(options){
		if(options.dataType=='json' || options.dataType=='png'){
			var waitIndex;
			if($.layer && ((typeof options.waitting=='undefined') || options.waitting)){//是否显示等待图标
				waitIndex=$.layer.load(0, {shade: 0.2});
			}
			if(!options.headers){
				options.headers={};
			}
			var tk=$.cookie('tK')||"Authorization";
			var tf=$.cookie("tF");
			var token=options.headers[tk];
			if(!token){
				var th=$.cookie("tH");
				if(tf && th){
					options.headers[tk]=th+" "+tf;
					updateTokenTime(tf, th);
				}
			}else{
				tf=token.substring(token.indexOf(' ')+1);
			}
			var datetime=new Date().getTime();
			options.headers.Datetime=datetime;
			options.headers.Language=$.config.language;
			options.headers.Website=$.config.website;
			options.headers.Version=$.config.version;
			if(!options.headers.upload){
				options.headers["Content-Type"]="application/json;charset=UTF-8";
				options.headers["Sign"]=dataSign(options, tf);
			}
			options.url=getServletPrefix(options.url)+options.url;
			var event=new AjaxEvent(options.dataType, options.success, options.error, waitIndex, options.headers);
			options.success=event.success;
			options.error=event.error;
		}
		return $.oldAjax(options);
	};
	function AjaxEvent(dataType, callback, failback, waitIndex, headers){
		this.dataType=dataType;
		this.callback=callback;
		this.failback=failback;
		this.waitIndex=waitIndex;
		var that=this;
		AjaxEvent.prototype.success=function(data){
			if(that.waitIndex){
				$.layer.close(that.waitIndex);
			}
			if(that.dataType=='json' && !headers.originalData){
				if(data.code=='0'){
					if(that.callback){
						that.callback(data.body);
					}
				}else if(data.code=='10000150'){//尚未登录
					window.location.href='/pages/admin/login.html?msg='+encodeURIComponent(data.message)+"&url="+encodeURIComponent(window.location.href);
				}else{
					console.log(that.failback);
					if(that.failback){
						var result=that.failback(data);
						if(result){
							$.error(data.message);
						}
					}else if($.layer){
						$.error(data.message);
					}else{
						window.alert(data.message);
					}
				}
			}else if(that.callback){
				that.callback(data);
			}
		};
		AjaxEvent.prototype.error=function(res){
			if(that.failback){
				var result=that.failback(data);
				if(result){
					$.error(data.message);
				}
			}else{
				console.log(res);
				$.error("请求错误");
			}
		};
	}
	layui.$.oldAjax=layui.$.ajax;
	layui.$.ajax=function(options){
		if(options.dataType=='json' || options.dataType=='png'){
			var waitIndex;
			if($.layer && ((typeof options.waitting=='undefined') || options.waitting)){//是否显示等待图标
				waitIndex=$.layer.load(0, {shade: 0.2});
			}
			if(!options.headers){
				options.headers={};
			}
			var tk=$.cookie('tK')||"Authorization";
			var tf=$.cookie("tF");
			var token=options.headers[tk];
			if(!token){
				var th=$.cookie("tH");
				if(tf && th){
					options.headers[tk]=th+" "+tf;
					updateTokenTime(tf, th);
				}
			}else{
				tf=token.substring(token.indexOf(' ')+1);
			}
			var datetime=new Date().getTime();
			options.headers.Datetime=datetime;
			options.headers.Language=$.config.language;
			options.headers.Website=$.config.website;
			options.headers.Version=$.config.version;
			if(!options.headers.upload){
				options.headers["Content-Type"]="application/json;charset=UTF-8";
				options.headers["Sign"]=dataSign(options, tf);
			}
			options.url=getServletPrefix(options.url)+options.url;
			var event=new LayuiAjaxEvent(options.dataType,options.success,options.data?options.data.error:undefined, waitIndex, options.headers);
			if(options.data){
				delete options.data.errBack;
			}
			options.success=event.success;
			options.error=event.error;
		}
		return layui.$.oldAjax(options);
	};
	function LayuiAjaxEvent(dataType, callback, failback, waitIndex, headers){
		this.dataType=dataType;
		this.callback=callback;
		this.failback=failback;
		this.waitIndex=waitIndex;
		var that=this;
		LayuiAjaxEvent.prototype.success=function(data){
			if(that.waitIndex){
				$.layer.close(that.waitIndex);
			}
			if(that.dataType=='json' && !headers.originalData){
				if(data.code=='0'){
					data.code=parseInt(data.code);
					if(that.callback){
						that.callback(data);
					}
				}else if(data.code=='10000150'){//尚未登录
					window.location.href='/pages/admin/login.html?msg='+encodeURIComponent(data.message)+"&url="+encodeURIComponent(window.location.href);
					return ;
				}else{
					if(that.failback){
						that.failback(data);
						$.error(data.message);
					}else if($.layer){
						$.error(data.message);
					}else{
						window.alert(data.message);
					}
				}
			}else if(that.callback){
				that.callback(data);
			}
		};
		AjaxEvent.prototype.error=function(res){
			console.log(res);
			$.error("请求错误");
		};
	}
	$.post=function(url, args1, args2, args3, args4){
		var options;
		if(typeof args1=='function'){
			options={
				url:url,
				type:'POST',
				dataType:args2,
				success:args1,
				waitting:args3
			}
		}else{
			options={
				url:url,
				type:'POST',
				dataType:args3,
				data:args1?(typeof args1=='string')?args1:$.toJson(args1):null,
				success:args2,
				waitting:args4
			}
		}
		$.ajax(options);
	};
	$.put=function(url, args1, args2, args3, args4){
		var options;
		if(typeof args1=='function'){
			options={
				url:url,
				type:'PUT',
				dataType:args2,
				data:null,
				success:args1,
				waitting:args3
			}
		}else{
			options={
				url:url,
				type:'PUT',
				dataType:args3,
				data:args1?(typeof args1=='string')?args1:$.toJson(args1):null,
				success:args2,
				waitting:args4
			}
		}
		$.ajax(options);
	};
	$["delete"]=function(url, args1, args2, args3, args4){
		var options;
		if(typeof args1=='function'){
			options={
				url:url,
				type:'DELETE',
				dataType:args2,
				data:null,
				success:args1,
				waitting:args3
			}
		}else{
			options={
				url:url,
				type:'DELETE',
				dataType:args3,
				data:args1?(typeof args1=='string')?args1:$.toJson(args1):null,
				success:args2,
				waitting:args4
			}
		}
		$.ajax(options);
	};
	$.cookie=function(key,value,time){//获取cookie和设置cookie
		if(typeof value=='undefined'){
			var cookies=document.cookie;
			var index=cookies.indexOf(key+"=");
			if(index==-1){
				return false;
			}
			index=index+key.length+1;
			var last=cookies.indexOf(";", index);
			if(last==-1){
				last=cookies.length;
			}
			return $.trim(cookies.substring(index,last));
		}else{
			var date=new Date();
			date.setTime(date.getTime()+time);
			document.cookie=key+"="+value+";expires="+date.toGMTString();
		}
	};
	$.formToData=function(formId, arrayFields){
		formId=typeof formId=='string'?$("#"+formId):formId;
		var json={};
		var formParams=formId.serializeArray();
		var isArray;
		$.each(formParams, function(){
			if(this.value){
				if (json[this.name] != undefined) {
					if (!json[this.name].push) {
						json[this.name] = [json[this.name]];
					}
					json[this.name].push(this.value || '');
				} else {
					isArray=false;
					if(arrayFields){
						for(var j=0, length2=arrayFields.length;j<length2;j++){
							if(arrayFields[j]==this.name){
								isArray=true;
								break;
							}
						}
					}
					if(isArray){
						json[this.name] = [this.value || ''];
					}else{
						json[this.name] = this.value || '';
					}
				}
			}
		});
		return json;
	}
	$.formToJson=function(formId, arrayFields){
		formId=typeof formId=='string'?$("#"+formId):formId;
		var json={};
		var formParams=formId.serializeArray();
		var isArray;
		$.each(formParams, function(){
			if(this.value){
				if (json[this.name] != undefined) {
					if (!json[this.name].push) {
						json[this.name] = [json[this.name]];
					}
					json[this.name].push(this.value || '');
				} else {
					isArray=false;
					if(arrayFields){
						for(var j=0, length2=arrayFields.length;j<length2;j++){
							if(arrayFields[j]==this.name){
								isArray=true;
								break;
							}
						}
					}
					if(isArray){
						json[this.name] = [this.value || ''];
					}else{
						json[this.name] = this.value || '';
					}
				}
			}
		});
		return JSON.stringify(json);
	}
	/**
	 * 验证表单
	 * @param formId 表单id或者表单JQuery对象
	 * @param formRules 表单验证规则，规则如下：
	 * 			{
	 * 				[key]:[
	 * 					{ [key]为表单中属性名称
	 * 						required: true|false,是否必填，默认false
	 * 						minLength: number,最小长度
	 * 						maxLength: number,最大长度
	 * 						number: true|false,是否数字，默认false，等同于正则^[\-]?[\d]+([\.]{1}[\d]+)?$
	 * 						regexp: /\d/,匹配正则表达式
	 * 						negate: true|false,取反,默认false,目前只针对regexp属性验证，其它的请自行扩展
	 * 						autoRule: function(value, form){}, 自定义规则，为1函数，返回true表示验证通过，false表示验证不通过
	 * 						focus: focusName,当验证不通过时，获取焦点的表单元素
	 * 						message: '',提示消息
	 * 					},...
	 * 				],...
	 * 			}
	 */
	$.valiForm=function(formId, formRules){
		if(!formRules){
			return true;
		}
		formId=typeof formId=='string'?$("#"+formId):formId;
		var inputs, pass=true;
		for(var key in formRules){
			inputs=formId.find(".layui-form-item:visible [name='"+key+"']");
			if(!inputs.exists()){//如果不存在则不校验
				continue;
			}
			inputs.each(function(){
				if((this.nodeName=='INPUT' && (this.type.toLowerCase()=='text' || this.type.toLowerCase()=='hidden')) || this.nodeName=='SELECT' || this.nodeName=='TEXTAREA'){
					pass=valiRule(this.value, this, formRules[key], formId);
					if(!pass){
						return false;
					}
				}else if(this.nodeName=='INPUT' && (this.type.toLowerCase()=='radio' || this.type.toLowerCase()=='checkbox')){
					if(this.checked){
						pass=valiRule(this.value, this, formRules[key], formId);
						if(!pass){
							return false;
						}
					}
				}
			});
			if(!pass){
				break;
			}
		}
		return pass;
	}
	function valiRule(value, input, rules, form){
		var pass=true;
		if(rules){
			for(var i=0, length=rules.length; i<length; i++){
				if(!rules[i]){
					continue;
				}
				if(rules[i].required){//必填验证
					if(!value){
						$.error(rules[i].message);
						if(rules[i].focus){
							form.find("[name='"+rules[i].focus+"']").focus();
						}else{
							input.focus();
						}
						pass=false;
						break;
					}
				}
				if(!value){
					continue;
				}
				if(rules[i].minLength){//最小长度验证
					if(value.length<rules[i].minLength){
						valiRuleMessage(rules[i], input, form);
						pass=false;
						break;
					}
				}
				if(rules[i].maxLength){//最大长度验证
					if(value.length>rules[i].maxLength){
						valiRuleMessage(rules[i], input, form);
						pass=false;
						break;
					}
				}
				if(rules[i].number){//数字验证
					if(!/\d+/.test(value)){
						valiRuleMessage(rules[i], input, form);
						pass=false;
						break;
					}
				}
				if(rules[i].regexp){//正则验证
					var compare=rules[i].regexp.test(value);
					if((!rules[i].negate && !compare) || (rules[i].negate && compare)){
						valiRuleMessage(rules[i], input, form);
						pass=false;
						break;
					}
				}
				if(rules[i].autoRule){//自定义规则验证
					if(!rules[i].autoRule(value, form)){
						valiRuleMessage(rules[i], input, form);
						pass=false;
						break;
					}
				}
			}
		}
		return pass;
	}
	function valiRuleMessage(rule, input, form){
		$.error(rule.message);
		if(rule.focus){
			form.find("[name='"+rule.focus+"']").focus();
		}else{
			input.focus();
		}
	}
	$.width=function(){
		return document.documentElement.clientWidth||document.documentElement.offsetWidth||document.body.clientWidth||document.body.offsetWidth;
	};
	$.height=function(){
		return document.documentElement.clientHeight||document.documentElement.offsetHeight||document.body.clientHeight||document.body.offsetHeight;
	};
	$.loadFormAjax=function(formId, method, url, data, back){
		$.ajax({
			url:url,
			type:method,
			data:data,
			dataType:'json',
			success:function(data){
				$.loadFormData(formId, data, back);
			}
		});
	}
	$.loadFormData=function(formId, data, back){
		var form=$(formId);
		if(data){
			var field,value,nodeName;
			for(var key in data){
				field=form.find("[name='"+key+"']");
				if(field.exists()){
					nodeName=field[0].nodeName.toUpperCase();
					if(field.length==1){
						if(nodeName=='INPUT' || nodeName=='SELECT' || nodeName=='TEXTAREA'){
							if(field.attr('lay-skin')=='switch'){
								if(data[key]===true){
									field.attr("checked","checked");
								}else{
									field.removeAttr("checked");
								}
								field.val(data[key]||'');
							}else if(nodeName=='INPUT'){
								var type=field.attr('type').toLowerCase();
								if(type=='text' || type=='password' || type=='hidden'){
									field.val(data[key]||'');
								}else if(type=='checkbox'){
									var list=data[key];
									field.removeAttr("checked");
									console.log(list);
									for(var i=0, length=list.length; i<length; i++){
										if(list[i]==field.val()){
											field.attr("checked","checked");
											console.log('命中：'+list[i]);
											break;
										}
									}
								}else{
									if(data[key]==field.val()){
										field.attr("checked","checked");
									}else{
										field.removeAttr("checked");
									}
								}
							}else{
								field.val(data[key]||'');
							}
						}else{
							field.html(data[key]||'');
						}
					}else{
						var type=field.attr('type').toLowerCase();
						var multiple=field.attr('multiple');
						if(nodeName=='INPUT' && type=='checkbox' && multiple=='multiple'){
							var list=data[key];
							field.removeAttr("checked");
							field.each(function(){
								for(var i=0, length=list.length; i<length; i++){
									if(list[i]==this.value){
										this.checked=true;
										break;
									}
								}
							});
						}else{
							value=data[key]||'';
							field.each(function(){
								if(value==this.value){
									this.checked=true;
								}else{
									this.checked=false;
								}
							});
						}
					}
				}
			}
		}
		if(back){
			back(data, form);
		}
	}
	$.fn.exists=function(){
		if(this && this.length>0){
			return true;
		}
		return false;
	};
	$.fn.equals=function(node){
		if(this==node || this==node[0] || this[0]==node[0]){
			return true;
		}
		return false;
	};
	$.textHeight=function(text, unitHeight, maxWidth){
		var match=text.match(/\n/g);
		var length=!match?0:match.length;
		var height=((length+1)*unitHeight);
		var array=text.split('\n'),charLength,char;
		for ( var i = 0, length=array.length; i < array.length; i++) {
			charLength=0;
			for ( var j = 0, length2=array[i].length; j < length2; j++) {
				char=array[i].charCodeAt(j);
				if(char>256){
					charLength+=2;
				}else if(char==9){
					charLength+=8;
				}else if(char!=13){
					charLength++;
				}
			}
			height+=parseInt(charLength/maxWidth)*unitHeight;
		}
		return height;
	};
	$.hrefHash=function(value, replace){
		var hash=window.location.hash;
		if(typeof value=='undefined'){
			if(hash){
				var hashArray=hash.substring(1);
				hashArray=hashArray.split('|');
				return hashArray;
			}
			return null;
		}
		if(replace){
			
		}
	};
	$.selectComp=function(options){
		$.selectComp.options=options;
		var select=typeof options.selectShow=='string'?$(options.selectShow):options.selectShow;
		options.selectShow=select;
		options.select=typeof options.select=='string'?$(options.select):options.select;
		var dataList=options.dataList;
		var keyName=options.keyName||"key";
		var valueName=options.valueName||"value";
		var otherAttr=options.otherAttr;
		select.click(function(){
			$.selectComp.index=$.layer.open({
				type: 1,
				title: false,
				area: ["1000px","400px"],
				content: '<div id="selectComp" class="select-comp"></div>'
			});
			var comp=$("#selectComp");
			var html="";
			for(var i=0,length=dataList.length;i<length;i++){
				html+="<span class=\"comp-item\" key=\""+dataList[i][keyName]+"\"";
				if(otherAttr){
					for(var key in otherAttr){
						html+=" "+otherAttr[key]+"=\""+dataList[i][key]+"\"";
					}
				}
				html+=" onclick=\"$.selectComp.selected(this);\">"+dataList[i][valueName]+"</span>";
			}
			comp.html(html);
		});
	};
	$.selectComp.selected=function(option){
		var option=$(option);
		$.selectComp.options.select.val(option.attr("key"));
		$.selectComp.options.selectShow.val(option.html());
		if(typeof $.selectComp.options.selected!='undefined'){
			$.selectComp.options.selected(option, $.selectComp.original);
		}
		$.selectComp.selectedOption=undefined;
		$.layer.close($.selectComp.index);
	};
	$.printParam=function(obj){
		for(var key in obj){
			console.log(key+"="+obj[key]);
		}
	};
	$.toJson=function(data, format){
		return JSON.stringify(data, null, format);
	};
	$.jsonEval=function(json){
		return window.eval('('+json+')');
	};
	$.parseHrefParam=function(key){
		var href=window.location.href;
		var index=href.indexOf('#');
		if(index!=-1){
			var param=href.substring(index+1);
			params=param.split('&');
			var paramObj={}, paramItem;
			for(var i=0, length=params.length;i< length;i++){
				paramItem=params[i].split('=');
				paramObj[paramItem[0].trim()]=decodeURIComponent(paramItem[1]||'').trim();
			}
			if(key){
				return paramObj[key];
			}else{
				return paramObj;
			}
		}
		index=href.indexOf('?');
		if(index!=-1){
			var param=href.substring(index+1);
			params=param.split('&');
			var paramObj={}, paramItem;
			for(var i=0, length=params.length;i< length;i++){
				paramItem=params[i].split('=');
				paramObj[paramItem[0].trim()]=decodeURIComponent(paramItem[1]||'').trim();
			}
			if(key){
				return paramObj[key];
			}else{
				return paramObj;
			}
		}
		return null;
	};
	$.setHrefParam=function(key, value){
		var params=$.parseHrefParam();
		if(!params){
			params={};
		}
		params[key]=value;
		var href=window.location.href;
		var index=href.indexOf('#');
		if(index!=-1){
			href=href.substring(0, index);
		}
		index=0;
		for(var pkey in params){
			href+=(index==0?'#':'&')+pkey+"="+params[pkey];
			index++;
		}
		window.location.href=href;
	};
	$.uuid=function() {
	    var s = [];
	    var hexDigits = "0123456789abcdef";
	    for (var i = 0; i < 36; i++) {
	        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	    }
	    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	    s[8] = s[13] = s[18] = s[23] = "-";
	 
	    var uuid = s.join("");
	    return uuid.replace(/-/g, '').toUpperCase();
    };
    $.dateFormat=function(date, format){
		if(typeof date=='string'){
			format=date;
			date=new Date();
		}
		const year = date.getFullYear().toString().padStart(4, '0').substring(2);
		const fullYear = date.getFullYear().toString().padStart(4, '0');
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		const hour = date.getHours().toString().padStart(2, '0');
		const minute = date.getMinutes().toString().padStart(2, '0');
		const second = date.getSeconds().toString().padStart(2, '0');
		return format.replace(/yyyy/g, fullYear).replace(/yy/g, year).replace(/MM/g, month).replace(/dd/g, day).replace(/HH/g, hour).replace(/mm/g, minute).replace(/ss/g, second);
	};
	$.timeConvert=function(time){
		if(time<0){
			return '0毫秒'
		}else if(time<1000){
			return time+"毫秒";
		}else if(time<60*1000){
			return (time*1.0/1000).toFixed(2)+"秒";
		}else if(time<60*60*1000){
			return (time*1.0/60/1000).toFixed(2)+"分";
		}else if(time<24*60*60*1000){
			return (time*1.0/60/60/1000).toFixed(2)+"小时";
		}else{
			return (time*1.0/24/24/60/1000).toFixed(2)+"天";
		}
	};
	$.success=function(content){
		$.layer.msg(content,{icon: 1,skin: "layui-layer-molv"});
	};
	$.error=function(content){
		$.layer.msg(content,{icon: 2});
	};
	$.warn=function(content){
		$.layer.msg(content,{icon: 0});
	};
	$.resize=[];
	$(window).on('resize', function() {
		if($.resize){
			for(var i=0, length=$.resize.length; i < length; i++){
				$.resize[i].method($.resize[i].args);
			}
		}
	});
	function updateTokenTime(tf, th){
		if(!tf){
			tf=$.cookie("tF");
			th=$.cookie("tH");
		}
		var expire=parseInt($.cookie("tE"));
		$.cookie("tF", tf, expire);
		$.cookie("tH", th, expire);
	}
	function getServletPrefix(url){
		var server, domain, routes;
		for(var i=0, length=$.config.domains.length; i<length; i++){
			domain=$.config.domains[i];
			routes=domain.routes;
			for(var j=0, length2=routes.length; j< length2; j++){
				if(url.startsWith(routes[j])){
					server=domain.server;
					break;
				}
			}
			if(server){
				break;
			}
		}
		if(!server){
			throw new Error("无法确定请求地址")
		}
		return server;
	}
    function dataSign(options, token){
		var sourceData=options.url;
		if(options.data){
			if(typeof options.data=='string'){
				sourceData+=options.data;
			}else{
				var index=0;
				for(var key in options.data){
					sourceData+=(index==0?'?':'&')+key+'='+options.data[key];
					index++;
				}
			}
		}
		sourceData+=options.headers.Datetime;
		sourceData+=options.headers.Website;
		sourceData+=options.headers.Language;
		sourceData+=options.headers.Version;
		if(!token){
			token=getDefaultKey();
		}
		sourceData+=token;
		//console.log('sign-data:'+sourceData);
		return md5(sourceData);
	}
	
	function getDefaultKey(){
		var keyArray=[48,51,55,68,56,56,57,54,65,55,55,67,52,53,53,53,57,48,69,70,51,50,68,48,68,67,51,55,65,54,69,69];
		var key='';
		for(var i=0,length=keyArray.length;i<length;i++){
			key+=String.fromCharCode(keyArray[i]);
		}
		return key;
	}
})()